package com.bjc.base.web;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

import com.bjc.base.bean.request.BookStockUpdateReqVO;
import com.bjc.base.service.*;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.bjc.base.bean.ResultVO;
import com.bjc.base.bean.request.BookCartReqVO;
import com.bjc.base.bean.request.BookStockReqVO;
import com.bjc.base.bean.request.BorrowReturnLogReqVO;
import com.bjc.base.bean.response.BookCartVO;
import com.bjc.base.bean.response.BookStockVO;
import com.bjc.base.core.ResultGenerator;
import com.bjc.base.utils.StringUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;

/**
 * <p>
 * 绘本购物车 前端控制器
 * </p>
 *
 * @author 许自辉
 * @since 2018-06-10
 */
@RestController
@RequestMapping("api/book")
@Api(value = "bookCart-api", tags = { "绘本购物车相关接口" })
public class BookCartController {
	@Autowired
	private IBookService bookService;
	@Autowired
	private IBookCartService bookCartService;
	@Autowired
	private IBorrowReturnLogService borrowReturnLogService;
	@Autowired
	private IBookStockService bookStockService;
	@Autowired
	private IBookStockUpdateService bookStockUpdateService;

	@ApiOperation("分页查询绘本购物车")
	@GetMapping("bookCart/findPage")
	public ResultVO getBookCartPage(@RequestParam("pageNum") int pageNum, @RequestParam("pageSize") int pageSize,
			BookCartReqVO bookCartReqVO) {
		PageHelper.startPage(pageNum, pageSize);
		List<BookCartVO> bookCartVOs = bookCartService.getList(bookCartReqVO);
		return ResultGenerator.getSuccess(new PageInfo<BookCartVO>(bookCartVOs));
	}

	@ApiOperation("分页查询绘本购物车")
	@GetMapping("bookCart/find")
	public ResultVO getBookCarte(BookCartReqVO bookCartReqVO) {
		BookCartVO bookCartVO = bookCartService.get(bookCartReqVO);
		return ResultGenerator.getSuccess(bookCartVO);
	}

	@ApiOperation("添加绘本购物车")
	@PostMapping("bookCart/create")
	public ResultVO createBookCart(@RequestBody BookCartReqVO bookCartReqVOs) {
		// 1.通过库存编码添加(二维码扫描借阅)
		// 2.通过库存id添加（续借）
		String bookCoded = bookCartReqVOs.getBCode();
		String bids = bookCartReqVOs.getBids();
		
		List<BookStockVO> bookStockVOs = new ArrayList<>();
		if (!StringUtil.isNullOrEmpty(bids)) {
			String[] bidss = bids.split(",");
			for (int i = 0; i < bidss.length; i++) {
				BookStockReqVO bookStockReqVO = new BookStockReqVO();
				// bookStockReqVO.setIsLock(0); // 正常未被借阅
				bookStockReqVO.setId(Integer.parseInt(bidss[i]));
				BookStockVO bookStockVO = bookStockService.get(bookStockReqVO);
				
				// 如果该借阅点为空，则默认归档到办公室
				if(bookStockVO.getPid() == null) {
//					bookStockReqVO.setBid(bid);
//					bookStockService.update(bookStockReqVO);
				}
				
				if (bookStockVO == null) {
					ResultGenerator.getFail("该绘本不存在：" + bookCoded);
				}
				bookStockVOs.add(bookStockVO);
				
				// 清空之前续借的记录，只要本次
				BookCartReqVO bookCartReqVO = new BookCartReqVO();
				bookCartReqVO.setUid(bookCartReqVOs.getUid());
				bookCartReqVO.setCartType("renew");
				bookCartService.delete(bookCartReqVO);
			}
		} else {
			// 通过绘本库存编码，从库存中拿到该书籍
			BookStockReqVO bookStockReqVO = new BookStockReqVO();
			// bookStockReqVO.setIsLock(0); // 正常未被借阅
			bookStockReqVO.setBookCode(bookCoded);
			BookStockVO bookStockVO = bookStockService.get(bookStockReqVO);
			if (bookStockVO == null) {
				return ResultGenerator.getFail("该绘本不存在：" + bookCoded);
			}
//			if (bookStockVO.getIsLock() == 1) {
//				return ResultGenerator.getFail("该绘本已被借阅：" + bookCoded);
//			}
			bookStockVOs.add(bookStockVO);
		}

		for (BookStockVO bookStockVO : bookStockVOs) {
			Integer borrowWeeks = bookCartReqVOs.getBorrowWeeks();
			bookCartReqVOs.setBorrowWeeks(null);
			bookCartReqVOs.setBid(bookStockVO.getId());
			bookCartReqVOs.setPid(bookStockVO.getPid());
			
			// 先查询该书是否添加到了购物车，不能重复添加，还有不能超过5本？
			BookCartVO bookCartVO = bookCartService.get(bookCartReqVOs);

			if (bookCartVO == null) {
				bookCartReqVOs.setBorrowWeeks(borrowWeeks);
				bookCartService.insert(bookCartReqVOs);
			} else {
				return ResultGenerator.getFail("你的购物车已存在当前绘本！");
			}
		}

		return ResultGenerator.getInsertSuccess(bookStockVOs.size());
	}

	@ApiOperation("更新绘本购物车")
	@PutMapping("bookCart/update")
	public ResultVO updateBookCart(@RequestBody BookCartReqVO bookCartReqVOs) {
		Integer replaceId = bookCartReqVOs.getReplaceId();
		if(replaceId!=null) {
			// 批量修改绘本的借阅点id
			String bids = bookCartReqVOs.getBids();
			if(StringUtils.isNoneBlank(bids)) {
				String[] bidss = bids.split(",");
				for (int i = 0; i < bidss.length; i++) {
					int bid = Integer.parseInt(bidss[i]);
					BookStockReqVO bookStockReqVO = new BookStockReqVO();
					bookStockReqVO.setId(bid);
					bookStockReqVO.setPid(replaceId);
					bookStockReqVO.setUpdateTime(LocalDateTime.now());
					bookStockService.update(bookStockReqVO);
					
					// 删除购物车已经修改的
					BookCartReqVO bookCartReqVO = new BookCartReqVO();
					bookCartReqVO.setBid(bid);
					bookCartReqVO.setCartType("replace");
					bookCartService.delete(bookCartReqVO);
					
					//自动归还
					BorrowReturnLogReqVO borrowReturnLogReqVO = new BorrowReturnLogReqVO();
					borrowReturnLogReqVO.setBid(bid);
					borrowReturnLogReqVO.setState(2);
					borrowReturnLogService.update(borrowReturnLogReqVO);

					// 添加记录
					BookStockUpdateReqVO bookStockUpdateReqVO = new BookStockUpdateReqVO();
					bookStockUpdateReqVO.setPid(replaceId);
					bookStockUpdateReqVO.setStockId(bid);
					insertBookStockUpdate(bookStockUpdateReqVO);
				}
			}
		}else {
			int count = bookCartService.update(bookCartReqVOs);
			return ResultGenerator.getUpdateSuccess(count);
		}
		return null;
	}

	

	@ApiOperation("批量删除绘本购物车")
	@DeleteMapping("bookCart/deleteList")
	public ResultVO deleteBookCart(@ApiParam(value = "bookCart id集合") @RequestBody int[] ids) {
		int count = bookCartService.deleteList(ids);
		return ResultGenerator.getDeleteSuccess(count);
	}

	@ApiOperation("下架")
	@DeleteMapping("bookCart/xiajia")
	public ResultVO xiajiaBookCart(@ApiParam(value = "bookCart id集合") @RequestBody int[] bids) {
		int i = bookService.deleteList(bids);
		return ResultGenerator.getDeleteSuccess(i);
	}

	@Async
	public void insertBookStockUpdate(BookStockUpdateReqVO bookStockUpdateReqVO){
		bookStockUpdateService.insert(bookStockUpdateReqVO);
	}
}
